package com.example.boot.quartz.task;

import com.aliyun.service.UploadService;
import com.example.common.enums.RedisFileConstant;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.util.CollectionUtils;

import java.util.Set;

/**
 * 定时删除OOS中上传的多余的图片
 *
 * @author ding
 * @since 2024/7/16
 */
@Slf4j
public class DeleteImg extends QuartzJobBean {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private UploadService uploadService;

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
      log.info("执行定时删除图片信息...");

      //差集 查询出不在数据库中使用的图片信息
        Set<Object> set = redisTemplate.opsForSet().difference(RedisFileConstant.upload_file, RedisFileConstant.upload_db_file);

        if (!CollectionUtils.isEmpty(set)) {
            for (Object o : set) {
                String img = o.toString();
                //阿里云删除图片
                String fileName = img.substring(img.lastIndexOf("/")+1);
                log.info("删除图片名称为{}", img);
                Boolean flag = uploadService.delete(fileName);
//                Boolean flag = true;
                if (flag) {
                    //在redis中删除多余的图片信息
                    redisTemplate.opsForSet().remove(RedisFileConstant.upload_file, img);
                    log.info("图片删除成功.....");
                }

            }
        }

    }
}
